package com.sxyc.weixin.controller;

import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.sxyc.tintin.controller.CommonController;
import com.sxyc.tintin.model.Address;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.utils.WeixinUtil;

public class DestinationController extends ApiController {

	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
	 * ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		return WeixinUtil.getApiConfig();
	}
//	static final String URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
//	static final String URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?";
	public void index() {
		String code = getPara("code");
		System.out.println("code--->"+code);
		String openId = (String) getRequest().getSession().getAttribute("openId");
		System.out.println("openId--->"+openId);
		if(openId == null && code == null){
			System.out.println("redirect_uri--->"+PropKit.get("domain")+"/destination");
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/destination", true);
			redirect(url);
		}else{
			if(openId == null){
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
				System.out.println("openid :"+openId);
			}
		JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
		System.out.println("jsApiTicket--->"+jsApiTicket);
		String jsapi_ticket = jsApiTicket.getTicket();
		
		String nonce_str = create_nonce_str();
		// 注意 URL 一定要动态获取，不能 hardcode.
		String url = "http://" + getRequest().getServerName() // 服务器地址
				// + ":"
				// + getRequest().getServerPort() //端口号
				+ getRequest().getContextPath() // 项目名称
				+ getRequest().getServletPath();// 请求页面或其他地址
		String qs = getRequest().getQueryString(); // 参数
		if (qs != null) {
			url = url + "?" + (getRequest().getQueryString());
		}
		System.out.println("url>>>>" + url);
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket +
        "&noncestr=" + nonce_str +
        "&timestamp=" + timestamp +
        "&url=" + url;

		String signature = HashKit.sha1(str);

		System.out.println("appId " + ApiConfigKit.getApiConfig().getAppId()
				+ "  nonceStr " + nonce_str + " timestamp " + timestamp);
		System.out.println("url " + url + " signature " + signature);
		System.out.println("nonceStr " + nonce_str + " timestamp " + timestamp);
		System.out.println(" jsapi_ticket " + jsapi_ticket);
		System.out.println("nonce_str  " + nonce_str);
		setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
		setAttr("nonceStr", nonce_str);
		setAttr("timestamp", timestamp);
		setAttr("url", url);
		setAttr("signature", signature);
		setAttr("jsapi_ticket", jsapi_ticket);
		setAttr("openId", openId);
		render("destination.jsp");
		}
	}
	public void openId(){
		String code = getPara("code");
		System.out.println("code--->"+code);
		String openId = (String) getRequest().getSession().getAttribute("openId");
		System.out.println("openId--->"+openId);
		if(openId == null && code == null){
			System.out.println("redirect_uri--->"+PropKit.get("domain")+"/UnBind");
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/destination", true);
			redirect(url);
		}else{
			if(openId == null){
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
				System.out.println("openid :"+openId);
			}
		
		}
	}
/**
 * 预约导航
 * @return
 */
	public void destination(){
		String openId = getPara("openId");
		String address = getPara("address");
		String longitude = getPara("lng");
		String latitude =  getPara("lat");
		double lng=Double.parseDouble(longitude);
		double lat=Double.parseDouble(latitude);
		DeviceBinding user = DeviceBinding.dao.getWxUserByOpenId(openId);
		new Address().set("openId",openId).set("lng", longitude).set("lat",latitude)
				 .set("address", address).set("cat",3).set("deviceId", user.get("DeviceId")).set("status",0).save();
		int code = CommonController.navigate(openId,address,lng,lat);
		JSONObject jo = new JSONObject();
		System.out.println("code--->"+code);
		jo.put("code", code);
		renderJson(jo);
	}
	public void view_destination(){
		String openId = getPara("openId");
		String address = getPara("address");
		String longitude = getPara("lng");
		String latitude =  getPara("lat");
		double lng=Double.parseDouble(longitude);
		double lat=Double.parseDouble(latitude);
		int code = CommonController.navigate(openId,address,lng,lat);
		JSONObject jo = new JSONObject();
		System.out.println("code--->"+code);
		jo.put("code", code);
		renderJson(jo);
	}
	
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

}
